package com.my.study.collection;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/6/20 19:16
 **/
@Slf4j(topic = "c.TestWordCount")
public class TestWordCount {

    static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
    static final URL PATH = Thread.currentThread().getContextClassLoader().getResource("");

    public static void main(String[] args) {
        demo(
//                () -> new HashMap<String, Integer>(),
//                (Supplier<Map<String, LongAdder>>) ConcurrentHashMap::new,
                (Supplier<Map<String, Integer>>) ConcurrentHashMap::new,
                (map, words) -> {
                    for (String word : words) {
//                        map.computeIfAbsent(word, (key) -> new LongAdder()).increment();
                        map.merge(word, 1, Integer::sum);
                    }
                }
        );
    }


    /**
     * 创建具有字符的文件
     */
    private static void createFile() {
        int length = ALPHA.length();
        int count = 200;

        List<String> list = new ArrayList<>(length * count);

        for (int i = 0; i < length; i++) {
            char ch = ALPHA.charAt(i);
            for (int j = 0; j < count; j++) {
                list.add(String.valueOf(ch));
            }
        }

        Collections.shuffle(list);

        for (int i = 0; i < length; i++) {
            try {
                try (PrintWriter pw = new PrintWriter(
                        new OutputStreamWriter(
                                new FileOutputStream(PATH.getPath() + "/tmp/" + (i + 1) + ".txt")))) {

                    String collect = list.subList(i * count, (i + 1) * count)
                            .stream().collect(Collectors.joining("\n"));
                    pw.print(collect);
                }
            } catch (Exception e) {
                log.error("错误 {}", e);
            }

        }
    }


    public static <V> void demo(Supplier<Map<String, V>> supplier,
                                BiConsumer<Map<String, V>, List<String>> consumer) {
        Map<String, V> counterMap = supplier.get();
        List<Thread> ts = new ArrayList<>();

        for (int i = 0; i < 26; i++) {
            int idx = i;
            Thread thread = new Thread(() -> {
                List<String> words = readFromFile(idx);
                consumer.accept(counterMap, words);
            });
            ts.add(thread);
        }

        ts.forEach(t -> t.start());

        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(counterMap);
    }

    /**
     * 读取文件
     *
     * @param i
     * @return
     */
    public static List<String> readFromFile(int i) {
        List<String> words = new ArrayList<>();
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(PATH.getPath() + "/tmp/" + (i + 1) + ".txt")))) {
            while (true) {
                String word = in.readLine();
                if (word == null) {
                    break;
                }
                words.add(word);
            }

            return words;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
